﻿using InnoWeb.CEND.BL.Service.News;
using InnoWeb.CEND.Core.Model.News;
using InnoWeb.CEND.Data;
using InnoWeb.CEND.Data.Infrastructure;
using InnoWeb.CEND.UI.MVC.Areas.Admin.Models;
using InnoWeb.CEND.Web.Framework;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace InnoWeb.CEND.UI.MVC.Areas.Admin.Controllers
{
    public class NewsController : Controller
    {
        private static WebSiteContext _context;
        private static IUnitOfWork _unitOfWork;

        private static GenericRepository<NewsItem> _newsItemRepository;
        private static GenericRepository<NewsContent> _newsContentRepository;
        private static NewsItemService _newsItemService;
        private static NewsContentService _newsContentService;

        public NewsController()
        {
            _context = new WebSiteContext(ConfigurationManager.ConnectionStrings["CendDBConnection"].ConnectionString);
            _unitOfWork = new UnitOfWork(_context);

            _newsItemRepository = new GenericRepository<NewsItem>(_context);
            _newsContentRepository = new GenericRepository<NewsContent>(_context);

            _newsItemService = new NewsItemService(_unitOfWork, _newsItemRepository);
            _newsContentService = new NewsContentService(_unitOfWork, _newsContentRepository);
        }

        //
        // GET: /Admin/News/

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Index()
        {
            var itemList = _newsItemService.GetAllElements().ToList();
            var contentList = _newsContentService.GetAllElements().ToList();
            List<NewsModel> returnList = new List<NewsModel>();
            var list = (from nI in itemList
                        join nC in contentList on nI.Id equals nC.NewsItemId
                        select new
                        {
                            nI,
                            nC
                        });
            foreach (var item in list)
            {
                NewsModel obj = new NewsModel();
                obj.NewsContent = item.nC;
                obj.NewsItem = item.nI;
                returnList.Add(obj);
            }

            return View(returnList);
        }

        //
        // GET: /Admin/News/Details/5

        public ActionResult Details(int id)
        {
            var item = _newsItemService.GetElementById(id);
            var content = _newsContentService.GetAllElements().Where(a => a.NewsItemId == item.Id).FirstOrDefault();
            
            NewsModel obj = new NewsModel();
            obj.NewsContent = content;
            obj.NewsItem = item;
            return View(obj);
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Create()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Create(NewsModel model)
        {
            try
            {
                var img = Request.Files["fileUpload"];

                string fileName = Guid.NewGuid().ToString().Replace("-", "");
                string serverPath = Server.MapPath("~/Content/Images");
                //string imagesPath = serverPath + "Content\\Images\\";
                string thumbPath = Server.MapPath("~/Content/Images/Thumb");
                string fullPath = Server.MapPath("~/Content/Images/Full");

                ImageUploader.ImageSave(thumbPath, fullPath, img, fileName);

                // TODO: Add insert logic here
                NewsItem itemObj = model.NewsItem;
                itemObj.CreatedDate = DateTime.Today;
                itemObj.IsActive = true;
                itemObj.IsDeleted = false;
                itemObj.ModifiedDate = DateTime.Today;
                _newsItemService.CreateElement(itemObj);
                _newsItemService.SaveChanges();
                int a = itemObj.Id;

                NewsContent contentObj = model.NewsContent;
                contentObj.CreatedDate = DateTime.Today;
                contentObj.IsActive = true;
                contentObj.IsDeleted = false;
                contentObj.ModifiedDate = DateTime.Today;
                contentObj.ImageUrl = fileName + ".jpg";
                contentObj.NewsItemId = a;
                _newsContentService.CreateElement(contentObj);
                _newsContentService.SaveChanges();


                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Edit(int id)
        {
            var item = _newsItemService.GetElementById(id);
            var content = _newsContentService.GetAllElements().Where(a => a.NewsItemId == item.Id).FirstOrDefault();

            NewsModel obj = new NewsModel();
            obj.NewsContent = content;
            obj.NewsItem = item;
            return View(obj);
        }

        //
        // POST: /Admin/News/Edit/5

        [HttpPost]
        public ActionResult Edit(int id, NewsModel model)
        {
            try
            {
                var item = model.NewsItem;
                item.ModifiedDate = DateTime.Today;
                _newsItemService.UpdateElement(item);
                _newsItemService.SaveChanges();

                var content = model.NewsContent;
                content.NewsItemId = item.Id;
                content.ModifiedDate = DateTime.Today;


                var img = Request.Files["fileUpload"];

                if (img != null)
                {
                    string fileName = Guid.NewGuid().ToString().Replace("-", "");
                    string serverPath = Server.MapPath("~/Content/Images");
                    //string imagesPath = serverPath + "Content\\Images\\";
                    string thumbPath = Server.MapPath("~/Content/Images/Thumb/");
                    string fullPath = Server.MapPath("~/Content/Images/Full/");

                    ImageUploader.ImageSave(thumbPath, fullPath, img, fileName);

                    content.ImageUrl = fileName + ".jpg";
                }
                else
                {
                    content.ImageUrl = _newsContentService.GetElementById(model.NewsContent.Id).ImageUrl;
                }

                _newsContentService.UpdateElement(content);
                _newsContentService.SaveChanges();


                return View(model);
            }
            catch
            {
                return View();
            }
        }

        //
        // GET: /Admin/News/Delete/5
        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "None")]
        public ActionResult Delete(int id)
        {
            NewsModel mdl = new NewsModel();
            var newsItem = _newsItemService.GetElementById(id);
            var newsContent = _newsContentService.GetAllElements().Where(a => a.NewsItemId == id).FirstOrDefault();
            mdl.NewsContent = newsContent;
            mdl.NewsItem = newsItem;

            return View(mdl);
        }

        //
        // POST: /Admin/News/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                var newsItem = _newsItemService.GetElementById(id);
                var newsContent = _newsContentService.GetAllElements().Where(a => a.NewsItemId == id).FirstOrDefault();

                newsItem.IsDeleted = true;
                newsItem.IsActive = false;

                newsContent.IsDeleted = true;
                newsContent.IsActive = false;

                _newsItemService.UpdateElement(newsItem);
                _newsItemService.SaveChanges();

                _newsContentService.UpdateElement(newsContent);
                _newsContentService.SaveChanges();

                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
    }
}
